import React from 'react';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx'
import { Browser, BrowserHrm, Upload, RouteLayout } from 'weaver-mobile-page'
import { withRouter } from 'react-router-dom';
import { Tools, TextareaItem, Icon, Select, Accordion, List, InputItem, DatePicker, Modal, Toast, Button } from 'weaver-mobile';
import * as TaskMainApis from '../../../api/task/taskMain'

const FormItem = List.FormItem
const { DatePickerInput } = DatePicker
const getLabel = Tools.getLabel

@inject("newTaskStore", "taskCommonStore")
@withRouter
@observer
class NewTask extends React.Component {

    constructor(props) {
        super(props)
        this.state = { ...props }
    }

    componentWillMount() {
        this.setDefaultParam()
    }

    componentWillUnmount() {
        const { clearValues } = this.props.newTaskStore
        clearValues()
    }

    setDefaultParam = () => {
        const { changeSorttype, changeDatetype, changeTodoval, changeUrgentLevel, changeSupTask } = this.props.newTaskStore
        let paramstr = this.props.location.search
        if (paramstr) {
            let paramobj = {}
            let paramarr = paramstr.substring(1).split("&")
            paramarr.forEach((p, i) => {
                const key = p.split("=")[0]
                const val = p.split("=")[1]
                if (key === "sorttype") {
                    paramobj.sorttype = val
                } else if (key === "datetype") {
                    paramobj.datetype = val
                } else if (key === "parentid") {
                    TaskMainApis.getTaskDetail({
                        taskId: val
                    }).then(res => {
                        if (res.status == 1) {
                            changeSupTask([
                                {
                                    id: val,
                                    name: res.name
                                }
                            ])
                        }
                    })
                }
            })
            if (paramobj.sorttype) {
                changeSorttype(paramobj.sorttype)
            }
            if (paramobj.datetype) {
                changeDatetype(paramobj.datetype)
                if (paramobj.sorttype == "5") {
                    changeTodoval(paramobj.datetype)
                } else if (paramobj.sorttype == "3") {
                    changeUrgentLevel(paramobj.datetype)
                }
            }
        }

        const { changeCategory, changeMaxUploadSize, changePrincipal } = this.props.newTaskStore
        return Tools.callApi({
            url: "/api/workrelate/task/getTaskFileCategory",
            method: "GET",
            params: {},
            type: "json"
        }).then((data) => {
            if (data.status == 1) {
                changeCategory(data.secId)
                changeMaxUploadSize(data.maxsize)
                changePrincipal([{ id: data.userid, name: data.username }])
            }
        })
    }

    onSaveTask = () => {
        if (!this.checkParam()) {
            return
        }

        let requestParam = this.getNewTaskRequestParam()
        this.doSave(requestParam)
    }

    checkParam = () => {
        const { taskCommonStore } = this.props
        const { taskname, principal } = this.props.newTaskStore
        if (taskname.trim() == "" || taskname.trim() == "null") {
            taskCommonStore.warn(getLabel(504646, '任务名称不能为空'))
            return false
        }
        if (principal.length == 0) {
            taskCommonStore.warn(getLabel('508801', '责任人不能为空'))
            return false
        }
        return true
    }

    getNewTaskRequestParam = () => {
        const { taskname, principal, partner, todoval, supTask, urgentLevel, enddate, remark, relateTask,
            relateGoal, relateDoc, relateProcess, relateCustomer, relateProject, relateAttachment, sorttype, datetype } = this.props.newTaskStore

        let requestParam = {}

        requestParam.relateadd = "1"
        requestParam.sorttype = sorttype
        requestParam.datetype = datetype
        requestParam.taskName = taskname

        if (principal.length > 0) {
            let arr = []
            principal.forEach((d, i) => {
                arr.push(d.id)
            })
            requestParam.principalid = arr.join(",")
        }

        if (partner.length > 0) {
            let arr = []
            partner.forEach((d, i) => {
                arr.push(d.id)
            })
            requestParam.partnerid = arr.join(",")
        }

        requestParam.todoval = todoval

        if (supTask.length > 0) {
            let arr = []
            supTask.forEach((d, i) => {
                arr.push(d.id)
            })
            requestParam.parentid = arr.join(",")
        }

        requestParam.level = urgentLevel
        requestParam.lev = urgentLevel
        requestParam.enddate = enddate
        requestParam.remark = remark

        if (relateTask.length > 0) {
            let arr = []
            relateTask.forEach((d, i) => {
                arr.push(d.id)
            })
            requestParam.taskids = arr.join(",")
        }

        if (relateGoal.length > 0) {
            let arr = []
            relateGoal.forEach((d, i) => {
                arr.push(d.id)
            })
            requestParam.goalids = arr.join(",")
        }

        if (relateDoc.length > 0) {
            let arr = []
            relateDoc.forEach((d, i) => {
                arr.push(d.id)
            })
            requestParam.docids = arr.join(",")
        }

        if (relateProcess.length > 0) {
            let arr = []
            relateProcess.forEach((d, i) => {
                arr.push(d.id)
            })
            requestParam.wfids = arr.join(",")
        }

        if (relateCustomer.length > 0) {
            let arr = []
            relateCustomer.forEach((d, i) => {
                arr.push(d.id)
            })
            requestParam.crmids = arr.join(",")
        }

        if (relateProject.length > 0) {
            let arr = []
            relateProject.forEach((d, i) => {
                arr.push(d.id)
            })
            requestParam.projectids = arr.join(",")
        }

        if (relateAttachment.length > 0) {
            let arr = []
            relateAttachment.forEach((d, i) => {
                arr.push(d.id)
            })
            requestParam.relatedacc = arr.join(",")
        }

        return requestParam
    }

    doSave = (requestParam) => {
        const { taskCommonStore } = this.props
        const { changeIsSaving } = this.props.newTaskStore
        changeIsSaving(true)
        taskCommonStore.showLoading()
        TaskMainApis.addTask(requestParam).then((res) => {
            changeIsSaving(false)
            taskCommonStore.closeLoading()
            if (res.status == 1) {
                if (res.taskId) {
                    taskCommonStore.saveSuccess(1, () => {
                        // this.props.history.go(-1)
                        this.props.history.replace("/taskHome/taskDetail/" + res.taskId)
                    })
                }
            } else if (res.status == 2) {
                taskCommonStore.warn(getLabel(508882, '保存出错,您没有给已选上级目标新建下级目标的权限'))
            } else {
                taskCommonStore.warn(getLabel(508744, '保存出错,请重新尝试或联系管理员'))
            }
        })
    }

    render() {
        const { taskNewHrmPrincipalBrowserStore, taskNewHrmPartnerBrowserStore, taskNewSupTaskBrowserStore, taskNewRelateTaskBrowserStore,
            taskNewRelateGoalBrowserStore, taskNewRelateDocBrowserStore, taskNewRelateProcessBrowserStore,
            taskNewRelateCustomerBrowserStore, taskNewRelateProjectBrowserStore, taskNewRelateAttachmentBrowserStore,
            taskname, changeTaskname, todovalOptions, todoval, changeTodoval,
            principal, changePrincipal, partner, changePartner, supTask, changeSupTask, urgentLevelOptions, urgentLevel, changeUrgentLevel,
            enddate, changeEnddate, remark, changeRemark, relateTask, changeRelateTask,
            relateGoal, changeRelateGoal, relateDoc, changeRelateDoc, relateProcess, changeRelateProcess,
            relateCustomer, changeRelateCustomer, relateProject, changeRelateProject,
            relateAttachment, changeRelateAttachment, category, maxUploadSize, isSaving } = this.props.newTaskStore

        return (
            <div className="workrelate-mobile-new-task">
                <div className="content-wrapper">
                    <Accordion defaultActiveKey="0">
                        <Accordion.Panel header={getLabel('81711', '基本信息')} className="custom-header">
                            <List>
                                <FormItem
                                    required={!taskname}
                                    extra={<Icon type="editor" size="xxs" />}
                                    label={getLabel(1352, '任务名称')}
                                    line
                                    noBorder
                                    content={
                                        <TextareaItem
                                            value={taskname}
                                            placeholder={getLabel(508736, '请输入任务名称')}
                                            autoHeight
                                            onChange={v => changeTaskname(v)}
                                        />
                                    }
                                />
                            </List>

                            <List>
                                <FormItem
                                    noBorder
                                    line
                                    content={
                                        <Select
                                            value={todoval}
                                            options={todovalOptions}
                                            label={getLabel(382534, '标记Todo')}
                                            onChange={val => changeTodoval(val)}
                                        />
                                    }
                                />
                            </List>

                            <List>
                                <BrowserHrm
                                    store={taskNewHrmPrincipalBrowserStore}
                                    viewAttr={3}
                                    isSingle={true}
                                    hasAdvanceSerach
                                    label={getLabel(16936, '责任人')}
                                    type={1}
                                    onChange={(...arg) => {
                                        changePrincipal(arg[2])
                                    }}
                                    valueArray={principal}
                                />
                            </List>

                            <List>
                                <BrowserHrm
                                    store={taskNewHrmPartnerBrowserStore}
                                    isSingle={false}
                                    hasAdvanceSerach
                                    label={getLabel(15761, '参与人')}
                                    type={1}
                                    onChange={(...arg) => {
                                        changePartner(arg[2])
                                    }}
                                    valueArray={partner}
                                />
                            </List>

                            <List>
                                <Browser
                                    store={taskNewSupTaskBrowserStore}
                                    label={getLabel(23785, '上级任务')}
                                    type="wrltsk"
                                    dataParams={{ parentid: -1 }}
                                    linkUrl="/spa/workrelate/static/index.html?#/main/workrelate/task/taskDetail?id="
                                    onChange={(...arg) => {
                                        changeSupTask(arg[2])
                                    }}
                                    valueArray={supTask}
                                />
                            </List>

                            <List>
                                <FormItem
                                    noBorder
                                    line
                                    content={
                                        <Select
                                            value={urgentLevel}
                                            options={urgentLevelOptions}
                                            label={getLabel(15534, '紧急程度')}
                                            onChange={val => changeUrgentLevel(val)}
                                        />
                                    }
                                />
                            </List>

                            <List>
                                <FormItem
                                    label={getLabel(741, '结束日期')}
                                    noBorder
                                    line
                                    content={
                                        <DatePickerInput
                                            placeholder={getLabel(83869, '请输入')}
                                            mode={"date"}
                                            value={enddate}
                                            onChange={(val) => changeEnddate(val)}
                                        />
                                    }
                                />
                            </List>

                            <List className="border-none">
                                <FormItem
                                    extra={<Icon type="editor" size="xxs" />}
                                    label={getLabel(433, '描述')}
                                    line
                                    noBorder
                                    content={
                                        <TextareaItem
                                            placeholder={getLabel(83869, '请输入')}
                                            autoHeight
                                            value={remark}
                                            onChange={val => changeRemark(val)}
                                        />
                                    }
                                />
                            </List>
                        </Accordion.Panel>
                        <Accordion.Panel header={getLabel('22078', '相关信息')} className="custom-header">
                            <List>
                                <Browser
                                    store={taskNewRelateGoalBrowserStore}
                                    isSingle={false}
                                    label={getLabel(382586, '相关目标')}
                                    type="wrlgoal"
                                    onChange={(...arg) => {
                                        changeRelateGoal(arg[2])
                                    }}
                                    valueArray={relateGoal}
                                />
                            </List>

                            <List>
                                <Browser
                                    store={taskNewRelateTaskBrowserStore}
                                    isSingle={false}
                                    label={getLabel('33414', '相关任务')}
                                    type="wrltsk"
                                    onChange={(...arg) => {
                                        changeRelateTask(arg[2])
                                    }}
                                    valueArray={relateTask}
                                />
                            </List>

                            <List>
                                <Browser
                                    store={taskNewRelateDocBrowserStore}
                                    isSingle={false}
                                    label={getLabel('857', '相关文档')}
                                    type={37}
                                    onChange={(...arg) => {
                                        changeRelateDoc(arg[2])
                                    }}
                                    valueArray={relateDoc}
                                />
                            </List>

                            <List>
                                <Browser
                                    store={taskNewRelateProcessBrowserStore}
                                    isSingle={false}
                                    label={getLabel('22105', '相关流程')}
                                    type={152}
                                    onChange={(...arg) => {
                                        changeRelateProcess(arg[2])
                                    }}
                                    valueArray={relateProcess}
                                />
                            </List>

                            <List>
                                <Browser
                                    store={taskNewRelateCustomerBrowserStore}
                                    isSingle={false}
                                    label={getLabel(783, '相关客户')}
                                    type={7}
                                    onChange={(...arg) => {
                                        changeRelateCustomer(arg[2])
                                    }}
                                    valueArray={relateCustomer}
                                />
                            </List>

                            <List>
                                <Browser
                                    store={taskNewRelateProjectBrowserStore}
                                    isSingle={false}
                                    label={getLabel('782', '相关项目')}
                                    type={8}
                                    onChange={(...arg) => {
                                        changeRelateProject(arg[2])
                                    }}
                                    valueArray={relateProject}
                                />
                            </List>

                            <List className="formitem-upload">
                                <FormItem
                                    label={getLabel(22194, '相关附件')}
                                    line
                                    noBorder
                                    content={<Upload
                                        store={taskNewRelateAttachmentBrowserStore}
                                        datas={relateAttachment}
                                        uploadUrl={'/api/doc/upload/uploadFile2Doc?category=' + category}
                                        editable={true}
                                        // viewAttr={"1"}
                                        onChange={(ids, datas) => { changeRelateAttachment(datas) }}
                                        maxUploadSize={maxUploadSize}
                                        // maxFilesNumber={ 16 }
                                        // totalMaxUploadSize={ 300 }
                                        showUploader={true}
                                        showUploadTime={true}
                                        onItemClick={(file, idx, files) => {
                                            window.openLink.openDocument(file.fileid)
                                        }}
                                        onFileLoad={(file) => {
                                            window.openLink.getWeaverFile("/weaver/weaver.file.FileDownload?fileid=" + file.imagefileid + "&download=1")
                                        }}
                                    />}
                                />
                            </List>
                        </Accordion.Panel>
                    </Accordion>
                </div>
                <div className="foot-wrapper" onClick={this.onSaveTask}>
                    <Button type="primary" loading={isSaving ? true : false} disabled={isSaving ? true : false}>{getLabel(86, '保存')}</Button>
                </div>
            </div>
        )
    }
}

export default NewTask
